import React, { useState } from 'react';
import classnames from 'classnames';
import Transition from '../Transition';
import Icon from '../Icon';

export type AlertType = 'info' | 'success' | 'error' | 'warning';

export interface AlertProps {
  type?: AlertType;
  message?: string;
  description?: string | React.ReactNode;
  closable?: boolean;
  showIcon?: boolean;
  onClose?: React.MouseEventHandler<HTMLButtonElement>;
}

const Alert: React.FC<AlertProps> = ({
  type,
  message,
  description,
  closable,
  showIcon,
  onClose,
}) => {
  const [closed, setClosed] = useState(false);

  const alertCls = classnames('alert', {
    'alert-no-icon': !showIcon,
    [`alert-${type}`]: type,
    'alert-with-description': description,
  });

  const alertMesCls = classnames({
    'alert-message': true,
  });

  const alertDesCls = classnames({
    'alert-description': true,
  });

  const renderIcon = () => {
    const iconClasses = classnames('alert-icon', {
      [`alert-icon-${type}`]: type,
    });

    const types = {
      info: 'info-circle',
      success: 'check-circle',
      warning: 'exclamation-circle',
      error: 'times-circle',
    };

    const icon = types[type || 'info'] as any;
    return <Icon icon={icon} className={iconClasses} />;
  };

  const handleClose = (e: React.MouseEvent<HTMLButtonElement>) => {
    setClosed(true);
    onClose?.(e);
  };

  return (
    <Transition in={!closed} animation="zoom-in-top" timeout={300}>
      <div className={alertCls}>
        {showIcon ? renderIcon() : null}
        <span className={alertMesCls}>{message}</span>
        <span className={alertDesCls}>{description}</span>
        {closable ? (
          <button
            type="button"
            className="alert-close-icon"
            onClick={handleClose}
          >
            <Icon icon="times" />
          </button>
        ) : null}
      </div>
    </Transition>
  );
};

Alert.defaultProps = {
  type: 'info',
  closable: false,
  showIcon: true,
};

export default Alert;
